<template>
  <div>
    <el-card>
      <h3 style="text-align: center">导入</h3>
      <el-alert
        title="每次导入仅可添加1000名员工,姓名、手机、入职时间、聘用形式为必填项"
        type="warning"
        show-icon
      />
      <uploadExcel :before-upload="beforeUpload" :on-success="handleSuccess" />
    </el-card>
  </div>
</template>

<script>
import uploadExcel from '@/components/UploadExcel/index.vue'
import empInfo from '@/constant/employees'
import { importEmployees } from '@/api/employees'
function formatDateExcel(numb, format) {
  const time = new Date((numb - 1) * 24 * 3600000 + 1)
  time.setYear(time.getFullYear() - 70)
  const year = time.getFullYear() + ''
  const month = time.getMonth() + 1 + ''
  const date = time.getDate() - 1 + ''
  if (format && format.length === 1) {
    return year + format + month + format + date
  }
  return (
    year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
  )
}
const formatList = ['correctionTime', 'timeOfEntry']
export default {
  name: 'Import',
  components: { uploadExcel },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    async handleSuccess({ results, header }) {
      // 将results数组进行map
      const _arr = results.map((v) => {
        // 每次遍历生成新的对象
        const obj = {}
        for (const k in empInfo.empInfoCh) {
          // 将枚举的值给到key
          const currentKey = empInfo.empInfoCh[k]
          // 将遍历的元素的值 给到value
          const currentValue = v[k]
          // 如果key包括需要格式的数组
          if (formatList.includes(currentKey)) {
            // 将excel时间转成js代码
            currentValue = formatDateExcel(currentValue, '/')
          }
          // 赋值到新的对象
          obj[currentKey] = currentValue
        }
        return obj
      })
      // 发请求
      const res = await importEmployees(_arr)
      // 提示成功
      this.$message.success(res.message)
      // 跳转
      this.$router.push('/employees')
    }
  }
}
</script>

<style></style>
